﻿using SCM.Common;
using SCM.Common.Extensions;
using SCM.Model.DBEntity;
using SCM.Servie.IBusiness;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace SCM.Servie.Business
{
    /// <summary>
    /// 用户角色服务
    /// </summary>
    public class UserRoleService : IUserRoleService
    {
        private readonly DbContext dal = new DbContext();

        public bool Add(List<T_User_Role> userRoles)
        {
            return dal.Insert(userRoles);
        }

        public bool Delete(List<string> ids)
        {
            return dal.Deleteable<T_User_Role>().In(ids).ExecuteCommand() > 0;
        }

        public bool Delete(string companyId, string userId)
        {
            return dal.Deleteable<T_User_Role>().Where(p => p.CompanyID == companyId && p.UserID == userId).ExecuteCommand() > 0;
        }

        public T_User_Role GetById(string id)
        {
            return dal.Get<T_User_Role>(id);
        }

        public List<T_User_Role> GetList(string companyId, string userId)
        {
            Expression<Func<T_User_Role, bool>> whereExp = (a) => true;
            if (!string.IsNullOrWhiteSpace(companyId))
            {
                whereExp = whereExp.Compose((a) => a.CompanyID == companyId, Expression.AndAlso);
            }
            if (!string.IsNullOrWhiteSpace(userId))
            {
                whereExp = whereExp.Compose((a) => a.UserID == userId, Expression.AndAlso);
            }
            return dal.Queryable<T_User_Role>().Where(whereExp).ToList();
        }

        public PageData<T_User_Role> Query(string companyId, string userId, PageInfo page)
        {
            int count = 0;
            Expression<Func<T_User_Role, bool>> whereExp = (a) => true;
            if (!string.IsNullOrWhiteSpace(companyId))
            {
                whereExp = whereExp.Compose((a) => a.CompanyID == companyId, Expression.AndAlso);
            }
            if (!string.IsNullOrWhiteSpace(userId))
            {
                whereExp = whereExp.Compose((a) => a.UserID == userId, Expression.AndAlso);
            }

            List<T_User_Role> list = dal.Queryable<T_User_Role>().Where(whereExp).ToPageList(page.PageIndex, page.PageSize, ref count);
            page.DataCount = count;
            return new PageData<T_User_Role> { Data = list, Page = page };
        }

        public bool Update(T_User_Role model)
        {
            return dal.Modify(model);
        }
    }
}
